import logging
import os
from pathlib import Path
from logging.handlers import RotatingFileHandler

# 从config模块导入settings对象
from .config import settings

# 从settings对象获取配置
SERVICE_NAME = settings.SERVICE_NAME
# 从settings对象获取日志级别配置
LOG_LEVEL = settings.LOG_LEVEL
LOG_DIR = "logs"
LOG_FILENAME = "ragent.log"

# 创建日志目录
log_dir = Path(LOG_DIR)
log_dir.mkdir(parents=True, exist_ok=True)

# 配置日志格式
log_format = '%(asctime)s - %(name)s - %(levelname)s - [%(process)d:%(thread)d] - %(message)s'

# 获取主logger
logger = logging.getLogger(f"{SERVICE_NAME}")
logger.setLevel(getattr(logging, LOG_LEVEL))

# 清除已有的handler
if logger.handlers:
    logger.handlers.clear()

# 设置文件handler（带轮转功能）
file_handler = RotatingFileHandler(
    filename=log_dir / LOG_FILENAME,
    maxBytes=10 * 1024 * 1024,  # 10MB
    backupCount=5,  # 保留5个备份
    encoding='utf-8'
)
file_handler.setFormatter(logging.Formatter(log_format))
logger.addHandler(file_handler)

# 设置控制台handler
console_handler = logging.StreamHandler()
console_handler.setFormatter(logging.Formatter(log_format))
logger.addHandler(console_handler)

# 在 uvicorn.run() 之前设置，并确保使用 logging.WARNING
logging.getLogger("watchfiles").setLevel(logging.WARNING)

# 抑制uvicorn的一些日志
logging.getLogger("uvicorn.error").setLevel(logging.INFO)
logging.getLogger("uvicorn.access").setLevel(logging.INFO)

# 提供获取logger的函数
def get_logger(service: str):
    """获取指定服务的logger实例"""
    if service:
        return logging.getLogger(f"{SERVICE_NAME}.{service}")
    return logger

def log_structured(event: str, data: dict):
    """记录结构化日志"""
    logger.info(f"{event}: {data}")